package com.demo.workbook.service.impl;

import com.demo.workbook.entity.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @className: UserDetailServiceImpl
 * @copyright: menusifu
 * @description:自定义实现登录接口
 *
 * @author: hubin
 * @date: 2020/11/13
 * @version: 1.0
 */

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 自定义登录逻辑
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        if(!"admin".equals(userName)){
            throw  new UsernameNotFoundException("账号不存在！");
        }
        //实际开发中，MyUser是从数据库中查询出来的对象,这里默认用户名为admin，密码为123
        String encodePwd=passwordEncoder.encode("123");

        //实际开发中，用户权限是从数据库中查询出来的，这里设置用户所拥有的权限（admin、admin1）和角色（test，注意角色必须是ROLE_打头，只有这样hasRole("test")才可以判断）
        MyUser myUser=new MyUser(userName,encodePwd, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,admin1,ROLE_test"));


        return myUser;
    }




}
